package com.example.hp.ormapp;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.hp.ormapp.activity.CrmDetailActivity;
import com.example.hp.ormapp.adapter.CrmAdapter;
import com.example.hp.ormapp.base.BaseActivity;
import com.example.hp.ormapp.bean.CrmBean;
import com.example.hp.ormapp.cache.DiskCacheManager;
import com.example.hp.ormapp.util.NetWorkUtil;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongsheng.ormapp.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yalantis.jellytoolbar.listener.JellyListener;
import com.yalantis.jellytoolbar.widget.JellyToolbar;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.EasyPermissions;

import static com.example.hp.ormapp.Constants.CRM_CONTENT;


public class MainActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, OnRefreshListener, OnLoadMoreListener, TextView.OnEditorActionListener {


    private static final int RC_WRITE = 12;
    private JellyToolbar mToolbar;
    private RecyclerView mMainList;
    //private SearchView mSearchView;
    private List<CrmBean.RowsBean> rowsBeans = new ArrayList<>();
    private CrmAdapter crmAdapter;
    private SmartRefreshLayout mMainRefresh;
    private AppCompatEditText editText;
    private static final String TEXT_KEY = "text";
    private final String cacheJson = "cache_json";
    private String hasCacheKey = "has_cache";
    private DiskCacheManager cacheManager;
    private SharedPreferences hasCache;
    private int pages = 1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {

        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setJellyListener(jellyListener);
        mToolbar.getToolbar().setPadding(0, getStatusBarHeight(), 0, 0);
        editText = (AppCompatEditText) LayoutInflater.from(this).inflate(R.layout.edit_text, null);
        editText.setBackgroundResource(R.color.colorTransparent);
        editText.setOnEditorActionListener(this);
        mToolbar.setContentView(editText);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        mMainList = findViewById(R.id.main_list);
        mMainList.setLayoutManager(new LinearLayoutManager(this));
        crmAdapter = new CrmAdapter(R.layout.item_request, rowsBeans);
        crmAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        crmAdapter.setOnItemClickListener(this);
        mMainList.setAdapter(crmAdapter);
        mMainRefresh = findViewById(R.id.main_refresh);
        initSwipeRefresh();
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private JellyListener jellyListener = new JellyListener() {
        @Override
        public void onCancelIconClicked() {
            if (TextUtils.isEmpty(editText.getText())) {
                mToolbar.collapse();
            } else {
                editText.getText().clear();
            }
        }
    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(TEXT_KEY, editText.getText().toString());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        editText.setText(savedInstanceState.getString(TEXT_KEY));
        editText.setSelection(editText.getText().length());
    }

    private void initSwipeRefresh() {
        mMainRefresh.setRefreshHeader(new ClassicsHeader(this));
        mMainRefresh.setRefreshFooter(new ClassicsFooter(this));
        mMainRefresh.setOnRefreshListener(this);
        mMainRefresh.setOnLoadMoreListener(this);
    }

    @Override
    public void initData() {
        showWaitDialog("请稍候...");
        hasCache = getSharedPreferences("hasCache", MODE_PRIVATE);
        cacheManager = new DiskCacheManager(MyApp.getContext(), Constants.CRMLISTCACHE);
        checkAppPermission();
    }

    private void checkAppPermission() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            initDiskLruCache();
        } else {
            EasyPermissions.requestPermissions(this, "缓存需要存储权限", RC_WRITE, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RC_WRITE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//授权成功
                initCrmListData(10, "");
            } else {
                toast("获取权限失败");
            }
        }
    }

    private void initCrmListData(int pageNum, String searchTag) {
        Map<String, String> params = new HashMap<>();
        params.put("limit", pageNum + "");
        params.put("offset", "offset");
        params.put("order", "desc");
        params.put("sort", "creationtime");
        params.put("front", searchTag);
        JSONObject jsonObject = new JSONObject(params);
        OkGo.<String>post(CRM_CONTENT)
                .tag(this)
                .upJson(jsonObject)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        handler.sendMessage(handler.obtainMessage(0, response.body()));
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        handler.sendMessage(handler.obtainMessage(2, response.body()));
                    }
                });
    }

    private void initDiskLruCache() {
        if (NetWorkUtil.isNetworkConnected(this)) {
            initCrmListData(10, "");
        } else {
            mMainRefresh.setEnableRefresh(false);
            boolean aBoolean = hasCache.getBoolean(hasCacheKey, false);
            if (!aBoolean) {
                String jsonObject1 = cacheManager.getString(cacheJson);
                handler.sendMessage(handler.obtainMessage(0, jsonObject1));
            } else {
                initCrmListData(10, "");
            }
        }
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search_view, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_search);
        //通过MenuItem得到SearchView
        mSearchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        //搜索框
        SearchView.SearchAutoComplete tv = mSearchView.findViewById(R.id.search_src_text);
        tv.setTextColor(Color.WHITE);
        tv.setHintTextColor(Color.WHITE);
        //搜索按钮
        ImageView ivSearch1 = mSearchView.findViewById(R.id.search_button);
        ivSearch1.setImageResource(R.drawable.left_search);
        //关闭按钮
        ImageView ivClose = mSearchView.findViewById(R.id.search_close_btn);
        ivClose.setImageResource(R.drawable.search_clear);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(MainActivity.this, query, Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }*/

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).statusBarColor(R.color.title).init();
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 0:
                    dismissWaitDialog();
                    String obj = (String) message.obj;
                    cacheManager.put(cacheJson, obj);
                    Gson gson = new Gson();
                    CrmBean crmBean = gson.fromJson(obj, CrmBean.class);
                    List<CrmBean.RowsBean> rows = crmBean.getRows();
                    for (CrmBean.RowsBean rowsBean : rows) {
                        rowsBeans.add(rowsBean);
                    }
                    crmAdapter.setEmptyView(getEmptyView());
                    crmAdapter.notifyDataSetChanged();
                    if (mMainRefresh.isRefreshing()) {
                        mMainRefresh.finishRefresh();
                    }
                    mMainRefresh.finishLoadMore();
                    hasCache.edit().putBoolean(hasCacheKey, true);
                    break;
                case 2:
                    dismissWaitDialog();
                    String error = (String) message.obj;
                    toast(error);
                    if (mMainRefresh.isRefreshing()) {
                        mMainRefresh.finishRefresh();
                    }
                    crmAdapter.setEmptyView(getEmptyView());
                    mMainRefresh.finishLoadMore();
                    break;
                case 3:
                    dismissWaitDialog();
                    String cacheObj = (String) message.obj;
                    Gson cacheGson = new Gson();
                    CrmBean cacheCrmBean = cacheGson.fromJson(cacheObj, CrmBean.class);
                    List<CrmBean.RowsBean> cacheRows = cacheCrmBean.getRows();
                    for (CrmBean.RowsBean rowsBean : cacheRows) {
                        rowsBeans.add(rowsBean);
                    }
                    crmAdapter.setEmptyView(getEmptyView());
                    crmAdapter.notifyDataSetChanged();
                    break;
            }
            return false;
        }
    });

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        CrmBean.RowsBean rowsBean = rowsBeans.get(position);
        toActivity(CrmDetailActivity.class, "crmValue", rowsBean);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (rowsBeans.size() != 0) {
            rowsBeans.clear();
        }
        String keytag = editText.getText().toString().trim();
        if (TextUtils.isEmpty(keytag)) {
            initCrmListData(10, "");
        } else {
            initCrmListData(10, keytag);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        cacheManager.flush();
    }

    @Override
    public void onLoadMore(RefreshLayout refreshLayout) {
        if (rowsBeans.size() != 0) {
            rowsBeans.clear();
        }
        pages += 1;
        String keytag = editText.getText().toString().trim();
        if (TextUtils.isEmpty(keytag)) {
            initCrmListData(pages * 10, "");
        } else {
            initCrmListData(pages * 10, keytag);
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
            String keytag = editText.getText().toString().trim();
            if (TextUtils.isEmpty(keytag)) {
                toast("请输入搜索关键字");
                return false;
            }
            showWaitDialog("搜索中...");
            if (rowsBeans.size() != 0) {
                rowsBeans.clear();
            }
            initCrmListData(10, keytag);
            return true;
        }
        return false;
    }

    public View getEmptyView() {
        return getLayoutInflater().inflate(R.layout.empty_layout, null);
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstTime < 1800) {
                moveTaskToBack(true);
            } else {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
